<form class="layui-form" action="">
    <div class="layui-form-item">
        <label class="layui-form-label">演员名称</label>
        <div class="layui-input-block">
            <input type="text" name="title" required lay-verify="required" placeholder="请输入标题" autocomplete="off"
                class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">头像</label>
        <div class="layui-input-block">
            <i class="layui-icon layui-icon-upload" style="font-size: 30px; color: #1E9FFF;" id="upload"></i>
            <span id="res"></span>
            <input type="file" name="path" required lay-verify="required" style="display: none;" accept="image/*">
        </div>
    </div>


    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>

<script>
    //Demo
    layui.use(['form', 'jquery','layer'], function () {
        var form = layui.form;
        var $ = layui.jquery;
        var layer = layui.layer;

        // 为头像的uploads添加点击事件触发文本域的点击
        $("#upload").click(() => {
            $("input[name='path']").click();
        })

        // 监听选择文件
        $("input[name='path']").change(function (e) {
            if (e) {
                $("#res").html('选择一个文件')
            }
        })

        //监听提交
        form.on('submit(formDemo)', function (data) {
            try {
                let { title } = data.field;
                let path = $("input[name='path']")[0].files[0];

                // 使用表单数据
                if (title && path) {
                    let formData = new FormData();
                    formData.append('title', title);
                    formData.append('path', path);

                    $.ajax({
                        url: '/admin/role-add-do',
                        method: 'post',
                        data: formData,
                        contentType: false,
                        processData: false,
                        success: function (res) {
                            if (res == 'success') {
                                // 提示
                                layer.msg('新增成功');
                                // 重置表单
                                $('form')[0].reset();
                                // 清空结果
                                $("#res").html('');
                            } else {
                                layer.msg('新增失败!')
                            }
                        }
                    })
                }

                return false;
            } catch (err) {
                console.log(err);
                return false;
            }

        });

        form.render();
    });
</script>